package com.xwzj.collects.spider.utils;

import java.net.URL;

import org.junit.Test;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;

/**
 * WebClient 模拟浏览器请求页面元素
 * @author xianfeng.cai
 * @date 2019-04-04
 */
public class LoginDemo1 {

    private WebClient webClient;

	@Test
    public void login() throws Exception {
    	webClient = new WebClient();
        webClient.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko");
        // 获取指定登录页实体
        HtmlPage page = (HtmlPage) webClient.getPage("http://127.0.0.1:8888");
        // 获取用户名输入框 并 输入用户名
        HtmlInput input1 = (HtmlInput)page.getHtmlElementById("loginName");
        input1.focus();
        input1.setValueAttribute("admin");
        
        // 获取密码输入框 并 输入密码
        HtmlInput input2 = (HtmlInput) page.getHtmlElementById("password");
        input2.focus();
        input2.setValueAttribute("admin");
        
        // 获取登录按钮
        HtmlSubmitInput btn = (HtmlSubmitInput) page.getHtmlElementById("btn");
        webClient.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        btn.click();
        
        URL url = new URL("http://127.0.0.1:8888/user/get?name=LoginDemo1");
        WebRequest request = new WebRequest(url);
        WebResponse res = webClient.getWebConnection().getResponse(request);
        System.out.println(res.getContentAsString());
    }

}
